﻿@using System.ComponentModel.DataAnnotations;

<Form Model="@model"
      ValidateMode="FormValidateMode.Complex"
      OnFinish="OnFinish"
      OnFinishFailed="OnFinishFailed"
      LabelColSpan="8"
      WrapperColSpan="16">
    <FormItem Label="Class Name">
        <Input @bind-Value="@context.ClassName" />
    </FormItem>
    <FormItem Label="Students" Name="@nameof(context.Students)" Rules="[new(){ Min=1 }]">
        <Button OnClick="addRow" Type="ButtonType.Primary" Style="margin-bottom:16px" Size="ButtonSize.Small">
            Add a row
        </Button>
        <Table DataSource="context.Students" TItem="Student" Context="row" Size="TableSize.Small" HidePagination Bordered>
            <PropertyColumn Width="30%" Property="c=>c.Name">
                <FormItem Required>
                    <Input @bind-Value="@row.Name" />
                </FormItem>
            </PropertyColumn>
            <PropertyColumn Property="c=>c.Address">
                <FormItem Required>
                    <Input @bind-Value="@row.Address" />
                </FormItem>
            </PropertyColumn>
        </Table>
    </FormItem>
    <FormItem WrapperColOffset="8" WrapperColSpan="16">
        <Button Type="ButtonType.Primary" HtmlType="submit">
            Submit
        </Button>
    </FormItem>
</Form>

<style>
    .ant-form-item-has-error .ant-table {
        border: 1px solid red;
    }
</style>

@code
{
    private Model model = new Model();

    public class Model
    {
        [Required]
        public string ClassName { get; set; }

        public List<Student> Students { get; set; } = [];
    }

    public record Student()
    {
        public string Id { get; set; }
        public string Age { get; set; }
        public string Name { get; set; }

        public string Address { get; set; }
    }

    void addRow()
    {
        model.Students.Add(new());
    }

    private void OnFinish(EditContext editContext)
    {
        Console.WriteLine($"Success:{JsonSerializer.Serialize(model)}");
    }

    private void OnFinishFailed(EditContext editContext)
    {
        Console.WriteLine($"Failed:{JsonSerializer.Serialize(model)}");
    }
}